<?php

/**
 * 计算竞拍者
 *
 * Created by PhpStorm.
 * User: evan
 * Date: 2016/11/23
 * Time: 下午12:26
 */
class Calculation extends MY_Cron_Controller
{
    /**
     * 计算竞拍中拍者
     *
     * php /data/www/shikee/web/cli.php auction/Calculation/index
     *
     * @return array
     */
    public function index()
    {
    	$i = 0;
    	while (true)
    	{
    		$this->run();
    		
    		$i++;
    		if($i>24){
    			return ;
    		}
    		
    		sleep(2);
    	}
    }
	
	
	public function run()
    {
        $where = array
        (
            'end_time<' => date('Y-m-d H:i:s', TIMESTAMP),
            'win_uid'   => 0,
            'status'    => AUCTION_STATUS_DOING,
            'is_public' => AUCTION_IS_ALLOW_PUBLIC_NOT,
        );


        $this->load->model('auction/Model_auction', 'a');
        $data = $this->a->lists(0, 1000, $where);


        foreach ($data as $k => $v)
        {
            $aid = (int)$v['aid'];
            if (!$aid)
            {
                continue;
            }


            //是否流拍
            $is_pass_in_rs = $this->is_pass_in($aid);
            if (200 != $is_pass_in_rs['status'])
            {
                $this->log('是否流拍检测错误, 竞拍ID:'.$aid.', 错误代码:'.$is_pass_in_rs['status']);
                return fur($is_pass_in_rs['data'], $is_pass_in_rs['status']);
            }


            //计算中奖者
            $calculation_shot_rs = $this->calculation_shot($aid);
            if (200 != $calculation_shot_rs['status'])
            {
                $this->log('计算中奖者错误, 竞拍ID:'.$aid.', 错误代码:'.$calculation_shot_rs['status']);
                return fur($calculation_shot_rs['data'], $calculation_shot_rs['status']);
            }


            //解冻未中拍用户的费用
            $thaw_not_shoot_fee_rs = $this->thaw_not_shoot_fee($aid);
            if (200 != $thaw_not_shoot_fee_rs['status'])
            {
                $this->log('解冻未中拍用户的费用错误, 竞拍ID:'.$aid.', 错误代码:'.$thaw_not_shoot_fee_rs['status']);
                return fur($thaw_not_shoot_fee_rs['data'], $thaw_not_shoot_fee_rs['status']);
            }
        }
    }


    /**
     * 是否流拍
     *
     * @param $aid
     * @return array
     */
    private function is_pass_in($aid)
    {
        $aid = (int)$aid;


        if (!$aid)
        {
            return fur(array(), 100002);
        }


        $this->load->model('auction/Model_auction', 'a');
        $item = $this->a->getById($aid);
        if (empty($item))
        {
            return fur(array(), 50008);
        }


        //查看竞拍的日志,如果日志为空则为流拍了
        $this->load->model('auction/Model_auction_log', 'al');
        $log_item = $this->al->getOne(array('aid' => $aid));
        if (!empty($log_item))
        {
            return fur(array());
        }


        //更新竞拍为流拍状态
        $save_rs = $this->a->save(array('status' => AUCTION_STATUS_PASS_IN), $aid);
        if (!$save_rs)
        {
            return fur(array(), 50034);
        }
        
        //推送消息
        $this->load->service('message/service_message_push');
        $replace_content = array(
        		'#anchor_name#'=>$item['uname'],
        		'#title#'=>$item['title'],
        		);
        $this->service_message_push->auction_racket($item['uid'], array('aid'=>$item['aid'], 'title'=>$item['title'], 'chat_room_num'=>$item['chat_room_num'], 'is_public' => $item['is_public']), $replace_content);

        return fur(array(), 50031);
    }


    /**
     * 中算中拍者
     *
     * @param $aid
     * @return array
     */
    private function calculation_shot($aid)
    {
        $aid = (int)$aid;


        if (!$aid)
        {
            return fur(array(), 100002);
        }


        $this->load->model('auction/Model_auction', 'a');
        $auction_info = $this->a->getById($aid);
        if (empty($auction_info))
        {
            return fur(array(), 50008);
        }


        $this->load->model('auction/Model_auction_log', 'al');
        $log_item = $this->al->getOne(array('aid' => $aid, 'is_thaw' => FINANCE_IS_THAW_NO), '*', 'amount desc');
        if (empty($log_item))
        {
            return fur(array(), 50032);
        }


        $this->load->model('user/Model_user', 'u');
        $user_item = $this->u->getById($log_item['uid']);
        if (empty($user_item))
        {
            return fur(array(), 10002);
        }


        //更新竞拍日志的竞拍状态
        $log_save_rs = $this->al->save(array('is_film' => AUCTION_IS_FILM_YES), $log_item['lid']);
        if (!$log_save_rs)
        {
            return fur(array(), 50033);
        }


        //关联竞拍成功用户
        $item = array
        (
            'status'     => AUCTION_STATUS_PENDING_HANDSHAKE,
            'win_uid'    => $log_item['uid'],
            'win_uname'  => $log_item['uname'],
            'win_time'   => now_time(),
            'win_amount' => $log_item['amount'],
        );
        $save_rs = $this->a->save($item, $aid);
        if (!$save_rs)
        {
            return fur(array(), 50034);
        }

        
        //创建直播
        $this->load->model('direct_seeding/Model_direct_seeding', 'ds');
        $create_rs = $this->ds->create($aid, $item['win_uid'], $auction_info['uid'],$auction_info['is_public'], $auction_info['is_charge'], $auction_info['amount'], $auction_info['ratio'], $auction_info['pic']);
        if (200 != $create_rs['status'])
        {
        	return sur($create_rs['data'], $create_rs['status']);
        }
        
        
        // 则创建新的对话
        $this->load->model('message/Model_message_dialogue', 'Model_message_dialogue');
        
        $where = array
        (
        		'(uid='.$item['win_uid'].' and to_uid='.$auction_info['uid'].') or (uid='.$auction_info['uid'].' and to_uid='.$item['win_uid'].')' => null,
        );
        
        $md_item = $this->Model_message_dialogue->getOne($where);
        
        if(!$md_item)
        {
        	$this->Model_message_dialogue->create($item['win_uid'], $auction_info['uid'], '私信通道已经建立，现在可以自由交流了！');
        }
        
        //建立私信通道
    	$this->load->model('user/Model_user_friend', 'uf');
        $where = array
        (
            'uid'        => $item['win_uid'],
            'friend_uid' => $auction_info['uid'],
        );
        $friend_item = $this->uf->getOne($where);


        if (empty($friend_item))
        {
            $this->uf->create($item['win_uid'], $auction_info['uid'], true);
        }
        else
        {
        	if($friend_item['private_channel'] == USER_FRIEND_PRIVATE_CHANNEL_NO)
        	{
        		$this->uf->save(array('private_channel' => USER_FRIEND_PRIVATE_CHANNEL_YES), $friend_item['fid']);
        	}
        }

        // 创建聊天室
        $ds_id = $create_rs['data']['ds_id'];
        
        $this->load->service('message/service_message_im');
        $chat_room_num = $this->service_message_im->group_create_group($ds_id);
        
        if(200 == $chat_room_num['status'])
        {
        	$this->ds->save(array('chat_room_num' => $chat_room_num['data']['GroupId']), $ds_id);
        }


        //与用户的交互 推送 短信
        $this->load->service('interactive/service_interactive_base');
        $this->service_interactive_base->interactive(array('type' => INTERACTIVE_AUCTION_SUCCESS, 'aid' => $aid));

		/*
        //解冻竞拍金额
        $this->load->model('finance/Model_finance_base_log', 'fbl');
        $thaw_rs = $this->fbl->thaw($log_item['uid'], $log_item['lid'], FINANCE_BUSINESS_AUCTION, 'THAW_AUCTION', '解冻_竞拍');
        if (200 != $thaw_rs['status'])
        {
            return fur($thaw_rs['data'], $thaw_rs['status']);
        }


        //解冻竞拍日志
        $al_thaw_rs = $this->al->thaw($log_item['lid']);
        if (200 != $al_thaw_rs['status'])
        {
            return fur($al_thaw_rs['data'], $al_thaw_rs['status']);
        }


        //扣除用户竞拍金额
        $this->load->model('finance/Model_finance_base_log', 'fbl');
        $defray_rs = $this->fbl->defray(
            $log_item['uid'],
            $log_item['amount'],
            CURRENCY_SGD,
            $log_item['lid'],
            '竞拍支出',
            'DEFRAY_AUCTION',
            FINANCE_BUSINESS_AUCTION,
            $log_item['uname'].'竞拍 支出'
        );


        if (200 != $defray_rs['status'])
        {
            return fur($defray_rs['data'], $defray_rs['status']);
        }
        
        */

		echo $aid.'ok ';
        return fur(array());
    }


    /**
     * 解除未拍者的费用
     *
     * @param $aid
     * @return array
     */
    private function thaw_not_shoot_fee($aid)
    {
        $aid = (int)$aid;


        if (!$aid)
        {
            return fur(array(), 100002);
        }


        $this->load->model('auction/Model_auction', 'a');
        $item = $this->a->getById($aid);
        if (empty($item))
        {
            return fur(array(), 50008);
        }


        $this->load->model('auction/Model_auction_log', 'al');
        $where = array
        (
            'aid' => $aid,
            'is_thaw' => FINANCE_IS_THAW_NO,
            'is_film' => AUCTION_IS_FILM_NO,
        );
        $data = $this->al->lists(0, 10000, $where);
        foreach ($data as $k => $v)
        {
            //解冻竞拍日志
            $al_thaw_rs = $this->al->thaw($v['lid']);
            if (200 != $al_thaw_rs['status'])
            {
                $this->log($v['lid'].' 解冻竞拍日志失败, 错误内容:'.$al_thaw_rs['msg'].', 状态码:'.$al_thaw_rs['status']);
                continue;
                //return fur($al_thaw_rs['data'], $al_thaw_rs['status']);
            }


            //解冻竞拍金额
            $this->load->model('finance/Model_finance_base_log', 'fbl');
            $thaw_rs = $this->fbl->thaw($v['uid'], $v['lid'], FINANCE_BUSINESS_AUCTION, 'THAW_AUCTION', '解冻_竞拍');
            if (200 != $thaw_rs['status'])
            {
                $this->log($v['lid'].' 解冻竞拍金额失败, 错误内容:'.$al_thaw_rs['msg'].', 状态码:'.$al_thaw_rs['status']);
                continue;
                //return fur($thaw_rs['data'], $thaw_rs['status']);
            }
        }


        return fur(array());
    }
    
    /**
     * 等待申请握手
     */
    /*
    public function wait_apply_handshake()
    {
    	// 10分钟
    	$play_time = strtotime("+10 minutes");
    	$where = array
    	(
    			'status'    => AUCTION_STATUS_PENDING_HANDSHAKE,
    			'play_time>' => date('Y-m-d H:i:00', $play_time),
    			'play_time<' => date('Y-m-d H:i:59', $play_time),
    	);
    	
    	$this->load->model('auction/Model_auction', 'a');
    	$data = $this->a->lists(0, 1000, $where);
    	
    	$this->load->model('user/Model_user', 'u');
    	
    	foreach($data as $v){
    		
    		
    		$user_item = $this->u->getById($v['uid']);
    		
    		$this->load->service('message/service_message_push');
    		$this->service_message_push->wait_apply_handshake($v['win_uid'], array('aid'=>$v['aid'], 'cid'=>$v['cid']), array('#anchor_name#' => $user_item['nickname']));
    	}
    	
    	// 20分钟
    	$play_time = strtotime("+20 minutes");
    	$where = array
    	(
    			'status'    => AUCTION_STATUS_PENDING_HANDSHAKE,
    			'play_time>' => date('Y-m-d H:i:00', $play_time),
    			'play_time<' => date('Y-m-d H:i:59', $play_time),
    	);
    	 
    	$this->load->model('auction/Model_auction', 'a');
    	$data = $this->a->lists(0, 1000, $where);
    	 
    	$this->load->model('user/Model_user', 'u');
    	 
    	foreach($data as $v){
    	
    	
    		$user_item = $this->u->getById($v['uid']);
    	
    		$this->load->service('message/service_message_push');
    		$this->service_message_push->wait_apply_handshake($v['win_uid'], array('aid'=>$v['aid'], 'cid'=>$v['cid']), array('#anchor_name#' => $user_item['nickname']));
    	}
    	
    	// 30分钟
    	$play_time = strtotime("+30 minutes");
    	$where = array
    	(
    			'status'    => AUCTION_STATUS_PENDING_HANDSHAKE,
    			'play_time>' => date('Y-m-d H:i:00', $play_time),
    			'play_time<' => date('Y-m-d H:i:59', $play_time),
    	);
    	 
    	$this->load->model('auction/Model_auction', 'a');
    	$data = $this->a->lists(0, 1000, $where);
    	 
    	$this->load->model('user/Model_user', 'u');
    	 
    	foreach($data as $v){
    	
    	
    		$user_item = $this->u->getById($v['uid']);
    	
    		$this->load->service('message/service_message_push');
    		$this->service_message_push->wait_apply_handshake($v['win_uid'], array('aid'=>$v['aid'], 'cid'=>$v['cid']), array('#anchor_name#' => $user_item['nickname']));
    	}
    }
    */
}